<template>
  <div class="bg-form">
    <el-form
      :model="addForm"
      label-width="140px"
      :rules="addFormRules"
      ref="addForm"
    >
      <el-row>
        <el-col :span="12">精品上架信息</el-col>
      </el-row>
      <el-divider content-position="center"></el-divider>
      <el-row>
        <el-col :span="6">
          <el-form-item label="供应商名称:" prop="supplierName">
            <el-input
              disabled
              v-model="addForm.supplierName"
              clearable
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商编号:" prop="supplierCode">
            <el-input
              disabled
              v-model="addForm.supplierCode"
              clearable
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="精品编号:" prop="orderNo">
            <el-input
              v-model="addForm.orderNo"
              clearable
              disabled
              placeholder=""
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属门店:" prop="storeId">
            <el-select
              class="w-100"
              clearable
              v-model="addForm.storeId"
              placeholder="所属门店"
            >
              <el-option
                v-for="item in stores"
                :key="item.id"
                :value="item.id"
                :label="item.storeName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="精品名称:" prop="name">
            <el-input
              v-model="addForm.name"
              clearable
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="精品一级类别:" prop="appLargeIdOne">
            <el-select
              class="w-100"
              clearable
              v-model="addForm.appLargeIdOne"
              placeholder="请选择"
              @change="handleLargeOne"
            >
              <el-option
                v-for="item in oneList"
                :key="item.index"
                :value="item.id"
                :label="item.largeName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="精品二级类别:" prop="appLargeIdTwo">
            <el-select
              class="w-100"
              clearable
              v-model="addForm.appLargeIdTwo"
              @change="handleLargeTwo"
              placeholder="请选择"
            >
              <el-option
                v-for="item in twoList"
                :key="item.index"
                :value="item.id"
                :label="item.largeName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="精品资源:" prop="resource">
            <el-select
              class="w-100"
              clearable
              v-model="addForm.resource"
              placeholder="请选择"
            >
              <el-option
                v-for="item in getDict(['用品属性'])['用品属性']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="售价:" prop="currentPrice">
            <el-input
              v-model="addForm.currentPrice"
              clearable
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="18">
          <el-form-item label="车型:" prop="modelList">
            <CarModel
              class="w-100"
              v-model="modelList"
              ref="carModel"
              placeholder="车型组件"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="适用品牌:">
            <el-select
              class="w-100"
              clearable
              filterable
              v-model="addForm.carBrandId"
              @change="change($event, 'carBrandId')"
              placeholder="请选择"
            >
              <el-option
                v-for="item in allCarList.brandsList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="适用车系:">
            <el-select
              class="w-100"
              clearable
              @change="change($event, 'seriesId')"
              v-model="addForm.seriesId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in allCarList.seriesList"
                :key="item.id"
                :value="item.id"
                @change="change"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车系年份:">
            <el-select
              class="w-100"
              clearable
              @change="change($event, 'timeType')"
              v-model="addForm.timeType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in allCarList.timeTypeList"
                :key="item"
                :value="item"
                :label="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购成本:" prop="costPrice">
            <el-input
              v-model="addForm.costPrice"
              clearable
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="适合车型:">
            <el-select
              class="w-100"
              clearable
              multiple
              v-model="addForm.modelId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in allCarList.modelList"
                :key="item.id"
                :value="item.id"
                :label="item.modelName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="是否养护:"
            prop="curing"
          >
            <el-select
              class="w-100"
              clearable
              v-model="addForm.curing"
              placeholder="是否养护"
            >
              <el-option
                v-for="item in getDict(['是否'])['是否']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">用品属性</el-divider>
      <el-row>
        <div v-for="(item, index) in addForm.brandStyleList" :key="index">
          <el-row>
            <el-col :span="6">
              <el-form-item label="属性：">
                <el-select
                  class="w-100"
                  v-model="item.id"
                  placeholder="请选择属性"
                  @change="selectAttribute($event, index)"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.styleName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="属性选项：">
                <el-select
                  value-key="id"
                  class="w-100"
                  v-model="item.optionList"
                  placeholder="请选择属性选项"
                  multiple
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in item.options"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                style="width: 80px; text-align: center"
                v-if="index == 0"
              >
                <el-button
                  type="primary"
                  @click="addOptions()"
                  style="width: 80px"
                  >添加</el-button
                >
              </el-form-item>
              <el-form-item
                style="width: 80px; text-align: center"
                v-else-if="index != 0"
              >
                <el-button
                  type="primary"
                  @click="deleteOptions(index)"
                  style="width: 80px"
                  >删除</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-row>
      <el-divider content-position="left">图片上传</el-divider>
      <el-row style="margin-top: 20px">
        <el-form-item label="主图:" prop="bigPicture">
          <UploadImg
            :show-list="showList"
            @get-file-list="getList"
            v-model="addForm.bigPicture"
          />
        </el-form-item>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-form-item label="详情图:" prop="picture">
          <UploadImg
            :limit="6"
            :show-list="showListTwo"
            @get-file-list="getListTwo"
            v-model="addForm.picture"
          />
        </el-form-item>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="24" align="right">
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import UploadImg from './components/uplaod'
import { getDict } from '@/utils/index'
import {
  getOneList,
  getTwoList,
  getBrand,
  add,
  update,
  getDetails
} from '@/api/pre-sale/qualityManagement/quality'
import { CarModel } from '@/components/index' // 导入组件库
import { mapGetters } from 'vuex'

export default {
  props: ['id'],
  components: {
    UploadImg,
    CarModel
  },
  computed: {
    ...mapGetters(['stores', 'storesCalue', 'userInfo', 'allCarList'])
  },
  data() {
    return {
      getDict: getDict,
      brandList: [], // 属性
      oneList: [], // 一级
      twoList: [], // 二级
      modelList: [], // 品牌 车系 车型
      showList: [],
      showListTwo: [],
      getOneCat: [],
      tableData: [
        {
          storeName: 1
        }
      ],
      dict: {
        sites: ['订单类别'],
        types: ['PC端', 'APP端']
      },
      addForm: {
        supplierName: '',
        supplierCode: '',
        orderNo: '',
        storeId: '',
        name: '',
        curing: '',
        appLargeIdOne: '',
        appLargeIdTwo: '',
        resource: '',
        currentPrice: '',
        costPrice: '',
        carBrandId: '',
        seriesId: '',
        timeType: '',
        modelId: '',
        bigPicture: '', // 主图
        picture: '', // 详情图
        brandStyleList: [{ id: '', name: '', optionList: [] }]
      },
      addFormRules: {
        storeId: [{ required: true, message: '请选择', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        resource: [{ required: true, message: '请选择', trigger: 'blur' }],
        appLargeIdOne: [{ required: true, message: '请选择', trigger: 'blur' }],
        appLargeIdTwo: [{ required: true, message: '请选择', trigger: 'blur' }],
        currentPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        costPrice: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.$store.dispatch('others/setAllBrand')
  },
  async mounted() {
    this.getOneList()

    this.dict = getDict(this.dict.sites)
    if (this.id !== 'add') {
      this.detail(this.id)
    }
    if (this.userInfo.supplier) {
      const { supplierCode, supplierName } = this.userInfo
      this.addForm.supplierName = supplierName
      this.addForm.supplierCode = supplierCode
    }
  },
  methods: {
    isJSON(str) {
      if (typeof str === 'string') {
        try {
          var obj = JSON.parse(str)
          if (typeof obj === 'object' && obj) {
            return true
          } else {
            return false
          }
        } catch (e) {
          console.log('error：' + str + '!!!' + e)
          return false
        }
      }
    },
    async detail(id) {
      const { data } = await getDetails(id)
      const { userName, supplierCode, supplier } = this.userInfo
      data.brandStyleList = Array.isArray(data.brandStyleList)
        ? data.brandStyleList
        : this.isJSON(data.brandStyleList)
          ? JSON.parse(data.brandStyleList)
          : [{ id: '', name: '', optionList: [] }]
      this.getTwoList(data.appLargeIdOne)
      this.getBrand(data.appLargeIdTwo)
      this.$nextTick(() => {
        data.supplierName = data.supplierName || (supplier ? userName : '')
        data.supplierCode = data.supplierCode || (supplier ? supplierCode : '')

        this.change(data.carBrandId, 'carBrandId')
        this.change(data.seriesId, 'seriesId')
        this.change(data.timeType, 'timeType')

        setTimeout(() => {
          data.modelId = data.modelId&&data.modelId.split(',')||''
          this.addForm = data
          this.addForm.curing = this.addForm.curing == 1 ? true : false
        }, 500)

        // this.modelList = [
        //   data.carBrandId,
        //   data.seriesId,
        //   data.timeType,
        //   +data.modelId,
        // ]
        this.showList = (data.bigPicture && data.bigPicture.split(',')) || []
        this.showListTwo = (data.picture && data.picture.split(',')) || []
      })
    },
    // 选择属性
    selectAttribute(val, index) {
      // 有选择的时候
      if (val) {
        const obj = this.brandList.filter((item) => item.id === val)
        this.addForm.brandStyleList[index].options = obj[0].optionList
        this.addForm.brandStyleList[index].name = obj[0].styleName
        this.addForm.brandStyleList[index].optionList = []
      } else {
        this.addForm.brandStyleList[index].options = []
        this.addForm.brandStyleList[index].optionList = []
        this.addForm.brandStyleList[index].name = ''
      }
    },
    // 新增属性
    addOptions() {
      this.addForm.brandStyleList.push({ id: '', name: '', optionList: [] })
    },
    // 删除属性
    deleteOptions(value) {
      this.addForm.brandStyleList.splice(value, 1)
    },
    // 获取主图
    getList(val) {
      this.addForm.bigPicture = val.toString()
    },
    // 获取详情图
    getListTwo(val) {
      this.addForm.picture = val.toString()
    },
    // 一级类别change
    handleLargeOne(val) {
      if (val) {
        this.getTwoList(val)
      } else {
        this.twoList = []
        this.brandList = []
      }
      this.addForm.appLargeIdTwo = ''
      this.addForm.brandStyleList = [{ id: '', name: '', optionList: [] }]
    },
    handleLargeTwo(id) {
      if (id) {
        this.getBrand(id)
      } else {
        this.brandList = []
      }
      this.addForm.brandStyleList = [{ id: '', name: '', optionList: [] }]
    },
    // 保存
    async onSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.id !== 'add') {
            this.edit()
          } else {
            this.add()
          }
        }
      })
    },
    getParam() {
      this.addForm.curing = this.addForm.curing ? 1 : 0
      this.addForm.modelId = this.addForm.modelId.toString()
      return {
        ...this.addForm,
        brandStyleList: JSON.stringify(this.addForm.brandStyleList)
      }
    },
    // 新增
    async add() {
      const { success } = await add(this.getParam())
      if (success) {
        this.$router.push({ path: '/qualityManagement/qualityShelves' })
      }
    },
    // 编辑
    async edit() {
      const { success } = await update(this.getParam())
      if (success) {
        this.$router.push({ path: '/qualityManagement/qualityShelves' })
      }
    },
    // 一级类别
    async getOneList() {
      const { supplier, supplierCode } = this.userInfo
      const p = {}
      if (supplier) {
        p['supplier'] = supplierCode
      }
      const { success, data } = await getOneList(p)
      if (success) {
        this.oneList = data
      }
    },
    // 二级类别
    async getTwoList(val) {
      const { success, data } = await getTwoList(val)
      if (success) {
        this.twoList = data
      }
    },
    // 属性
    async getBrand(categoryId) {
      const params = {
        param: { categoryId: categoryId }
      }
      const { success, data } = await getBrand(params)
      if (success) {
        this.brandList = data.content || []
      }
    },
    change(id, type) {
      if(!id)return
      switch (type) {
        case 'carBrandId':
          this.$store.dispatch('others/setCleanCar', {
            seriesList: [],
            timeTypeList: [],
            modelList: []
          })
          this.$store.dispatch('others/setSeries', id)
          this.addForm = {
            ...this.addForm,
            carBrandId: id,
            seriesId: '',
            timeType: '',
            modelId: []
          }
          break
        case 'seriesId':
          this.$store.dispatch('others/setCleanCar', {
            timeTypeList: [],
            modelList: []
          })
          this.$store.dispatch('others/setModelTimeType', {
            brandId: this.addForm.carBrandId,
            seriesId: id
          })
          this.addForm = {
            ...this.addForm,
            seriesId: id,
            timeType: '',
            modelId: []
          }
          break
        case 'timeType':
          this.$store.dispatch('others/setCleanCar', {
            modelList: []
          })
          this.$store.dispatch('others/setModelRank', {
            brandId: this.addForm.carBrandId,
            seriesId: this.addForm.seriesId,
            timeType: id
          })
          this.addForm = {
            ...this.addForm,
            timeType: id,
            modelId: []
          }
          break
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.bg-form {
  background: #ffffff;
  padding: 20px;
}
</style>

